package cn.com.surker.workcon.service.bcs;

import cn.com.surker.base.system.dao.SysStorageLogDao;
import cn.com.surker.base.system.entity.SysLine;
import cn.com.surker.base.system.entity.SysStorageLog;
import cn.com.surker.control.entity.ControlExpend;
import cn.com.surker.database.JDBCTemplateCache;
import cn.com.surker.enums.StateEnum;
import cn.com.surker.lab.entity.LabExpend;
import cn.com.surker.lab.entity.LabExpendOther;
import cn.com.surker.lab.vo.LabExpendVoB;
import cn.com.surker.util.DateUtil;
import cn.com.surker.util.RandomUtils;
import cn.com.surker.util.StringUtils;
import cn.com.surker.workcon.common.GKJDBCService;
import cn.com.surker.workcon.service.DosageService;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 * 消耗信息 Mapper 接口
 * </p>
 *
 * @author admin
 * @since 2024-09-26
 */
public class DosageServiceImpl extends GKJDBCService implements DosageService {

	@Resource
	private SysStorageLogDao sysStorageLogDao;

	/**
	 * 根据盘id,查询工控机消耗信息
	 *
	 * @param pieId
	 * @param batchStere
	 * @return
	 */
	public List<LabExpend> findByPieId(Long lineId, Long invoiceId, Long batchId, String prodId, String pieId, Date batTime,
									   Double batchStere, Long formulaId, Double formulaWater, Long levelOptimizeId, Date createDate) {
		if (lineId == null || StringUtils.isBlank(pieId)) {
			return null;
		}
		SysLine line = getLine(lineId);
		if (line == null) {
			return null;
		}
		JdbcTemplate lineJdbcTemp = getLineJdbcTemp(line);
		//	查询sql
		String querySql = "select * from Dosage where PieID = '" + pieId + "'";
		List<Map<String, Object>> dosageList = lineJdbcTemp.queryForList(querySql);
		if (dosageList == null || dosageList.isEmpty()) {
			return null;
		}
		//	转换数据
		String batchTime = "";
		if (batTime != null) {
			batchTime = DateUtil.convertString(batTime);
		}
		List<LabExpend> expendList = new ArrayList<>();
		for (int i = 0, s = dosageList.size(); i < s; i++) {
			Map<String, Object> dosage = dosageList.get(i);
			//	工控机的记录号
			String conExpendId = String.valueOf(dosage.get("DosID"));
			//	工控机的料仓信息,根据料仓信息查询出当前消耗的材料
			String storage = String.valueOf(dosage.get("Storage"));
			//	工控机的原料
			String bcsMaterial = String.valueOf(dosage.get("Material"));
			//	erp的原料id
			Long erpMaterialId = null;
			//	工控机的原料id
			Long erpStorageId = null;
			SysStorageLog takeTimeOrStorage = sysStorageLogDao.findTakeTimeOrStorage(lineId, bcsMaterial, 1, batchTime);
			if (takeTimeOrStorage != null) {
				String erpMaterial = takeTimeOrStorage.getMaterial();
				erpMaterialId = takeTimeOrStorage.getMaterialId();
				erpStorageId = takeTimeOrStorage.getStorageId();
			}
			//	工控机的配方值
			Double recAmnt = Double.valueOf(String.valueOf(dosage.get("recAmnt")));
			//	工控机的设定值
			Double planAmnt = Double.valueOf(String.valueOf(dosage.get("planAmnt")));
			//	工控机的实际值
			Double factAmnt = Double.valueOf(String.valueOf(dosage.get("factAmnt")));
			//	工控机的含水率
			Double watFull = Double.valueOf(String.valueOf(dosage.get("watFull")));
			LabExpend expend = new LabExpend();
			expend.setInvoiceId(invoiceId);
			expend.setLineId(lineId);
			expend.setMaterialId(erpMaterialId);
			expend.setStorageId(erpStorageId);
			expend.setControlStorage(storage);
			expend.setControlMaterial(bcsMaterial);
			expend.setBatchId(batchId);
			expend.setFormulaId(formulaId);
			expend.setFormulaQuantity(recAmnt);
			expend.setFormulaWater(formulaWater);
			expend.setControlSetQuantity(planAmnt);
			expend.setControlRealQuantity(factAmnt);
			expend.setControlWater(watFull);
			expend.setCreator(bcsCreater);
			expend.setCreateTime(createDate);
			expend.setUseTime(batTime);
			expend.setConExpendId(conExpendId);
			expendList.add(expend);
		}
		return expendList;
	}

	@Override
	public List<ControlExpend> findWorkByPieId(Long lineId, Long batchId, String prodId, String pieId, Date batTime, Date createDate) {
		if (lineId == null || StringUtils.isBlank(pieId)) {
			return null;
		}
		SysLine line = getLine(lineId);
		if (line == null) {
			return null;
		}
		JdbcTemplate lineJdbcTemp = getLineJdbcTemp(line);
		//	查询sql
		String querySql = "select * from Dosage where PieID = '" + pieId + "'";
		List<Map<String, Object>> dosageList = lineJdbcTemp.queryForList(querySql);
		if (dosageList == null || dosageList.isEmpty()) {
			return null;
		}
		List<ControlExpend> expendList = new ArrayList<>();
		for (int i = 0, s = dosageList.size(); i < s; i++) {
			Map<String, Object> dosage = dosageList.get(i);
			//	工控机的记录号
			String conExpendId = String.valueOf(dosage.get("DosID"));
			//	工控机的料仓信息,根据料仓信息查询出当前消耗的材料
			String storage = String.valueOf(dosage.get("Storage"));
			//	工控机的原料
			String bcsMaterial = String.valueOf(dosage.get("Material"));
			String batchTime = "";
			if (batTime != null) {
				batchTime = DateUtil.convertString(batTime);
			}
			Long erpMaterialId = null;
			Long erpStorageId = null;
			SysStorageLog takeTimeOrStorage = sysStorageLogDao.findTakeTimeOrStorage(lineId, bcsMaterial, 1, batchTime);
			if (takeTimeOrStorage != null) {
				String erpMaterial = takeTimeOrStorage.getMaterial();
				erpMaterialId = takeTimeOrStorage.getMaterialId();
				erpStorageId = takeTimeOrStorage.getStorageId();
			}
			//	工控机的配方值
			Double recAmnt = Double.valueOf(String.valueOf(dosage.get("recAmnt")));
			//	工控机的设定值
			Double planAmnt = Double.valueOf(String.valueOf(dosage.get("planAmnt")));
			//	工控机的实际值
			Double factAmnt = Double.valueOf(String.valueOf(dosage.get("factAmnt")));
			//	工控机的含水率
			Double watFull = Double.valueOf(String.valueOf(dosage.get("watFull")));
			ControlExpend expend = new ControlExpend();
			expend.setLineId(lineId);
			expend.setErpBatchId(batchId);
			expend.setStorage(storage);
			expend.setMaterial(bcsMaterial);
			expend.setErpMaterialId(erpMaterialId);
			expend.setErpStorageId(erpStorageId);
			expend.setFormulaQuantity(recAmnt);
			expend.setControlSetQuantity(planAmnt);
			expend.setControlRealQuantity(factAmnt);
			expend.setControlWater(watFull);
			expend.setUseTime(batTime);
			expend.setStatus(StateEnum.ENABLED.getCode());
			expend.setCreator(bcsCreater);
			expend.setCreateTime(createDate);
			expend.setConExpendNo(conExpendId);
			expendList.add(expend);
		}
		return expendList;
	}

	@Override
	public List<LabExpendOther> findAll(Long lineId) {
		SysLine line = getLine(lineId);
		if (line == null) {
			return null;
		}
		JdbcTemplate lineJdbcTemp = getLineJdbcTemp(line);
		if (lineJdbcTemp == null) {
			return null;
		}
		//	查询数据
		//	查询sql
		String querySql = "select a.*,b.DatTim from Dosage a\n" +
			"left join Piece b ON a.PieID = b.PieID\n" +
			"left join Product c ON b.ProdID = c.ProdID\n" +
			" where c.erpid = 0 and c.dattim > '2024-12-25 07:00:00' and c.station = " + line.getControlLineId();
		List<Map<String, Object>> dosageList = lineJdbcTemp.queryForList(querySql);
		if (dosageList == null || dosageList.isEmpty()) {
			return null;
		}
		//	转换数据
		List<LabExpendOther> expendList = new ArrayList<>();
		for (int i = 0, s = dosageList.size(); i < s; i++) {
			Map<String, Object> dosage = dosageList.get(i);
			//	工控机的料仓信息,根据料仓信息查询出当前消耗的材料
			String storage = String.valueOf(dosage.get("Storage"));
			//	工控机的原料
			String bcsMaterial = String.valueOf(dosage.get("Material"));
			Date datTim = DateUtil.convertDate(String.valueOf(dosage.get("DatTim")));
			String taskTime = DateUtil.convertString(datTim);
			//	erp的原料id
			Long erpMaterialId = null;
			//	工控机的原料id
			Long erpStorageId = null;
			SysStorageLog takeTimeOrStorage = sysStorageLogDao.findTakeTimeOrStorage(lineId, bcsMaterial, 1, taskTime);
			if (takeTimeOrStorage != null) {
				String erpMaterial = takeTimeOrStorage.getMaterial();
				erpMaterialId = takeTimeOrStorage.getMaterialId();
				erpStorageId = takeTimeOrStorage.getStorageId();
			}
			//	工控机的配方值
			Double recAmnt = Double.valueOf(String.valueOf(dosage.get("recAmnt")));
			//	工控机的设定值
			Double planAmnt = Double.valueOf(String.valueOf(dosage.get("planAmnt")));
			//	工控机的实际值
			Double factAmnt = Double.valueOf(String.valueOf(dosage.get("factAmnt")));
			//	工控机的含水率
			Double watFull = Double.valueOf(String.valueOf(dosage.get("watFull")));
			//	创建erp手动消耗数据
			LabExpendOther labExpendOther = new LabExpendOther();
			labExpendOther.setLineId(lineId);
			labExpendOther.setMaterialId(erpMaterialId);
			labExpendOther.setStorageId(erpStorageId);
			labExpendOther.setDosage(factAmnt);
			labExpendOther.setExpendTime(datTim);
			labExpendOther.setStatus(StateEnum.ENABLED.getCode());
			labExpendOther.setRemark(storage);
			labExpendOther.setCreator(bcsCreater);
			labExpendOther.setCreateTime(new Date());
			expendList.add(labExpendOther);
		}
		return expendList;
	}

	@Override
	public LabExpend queryByDosId(Long lineId, Long batchId, String dosId) {
		if (lineId == null || StringUtils.isBlank(dosId)) {
			return null;
		}
		SysLine line = getLine(lineId);
		if (line == null) {
			return null;
		}
		JdbcTemplate lineJdbcTemp = getLineJdbcTemp(line);
		if (lineJdbcTemp == null) {
			return null;
		}
		//	查询sql
		String querySql = "select storage controlStorage,material controlMaterial,recAmnt formulaQuantity,planAmnt controlSetQuantity,factAmnt controlRealQuantity,watFull controlWater from Dosage where dosid = ?";
		Object[] params = {dosId};
		List<LabExpend> labExpends = lineJdbcTemp.query(querySql, params, BeanPropertyRowMapper.newInstance(LabExpend.class));
		if (labExpends == null || labExpends.isEmpty()) {
			return null;
		}
		LabExpend labExpend = labExpends.get(0);
		if (labExpend == null) {
			return null;
		}
		return labExpend;
	}

	@Override
	public List<Long> writeBackB(Long lineId, List<LabExpendVoB> labExpends) {
		if (lineId == null || labExpends == null || labExpends.isEmpty()) {
			return null;
		}
		SysLine line = getLine(lineId);
		//  获取b库数据的连接
		String standardUrl = line.getStandardUrl();
		String standardUsername = line.getStandardUsername();
		String standardPassword = line.getStandardPassword();
		if (StringUtils.isBlank(standardUrl) || StringUtils.isBlank(standardUsername)
			|| StringUtils.isBlank(standardPassword)) {
			return null;
		}
		line.setUrl(standardUrl);
		line.setUsername(standardUsername);
		line.setStandardPassword(standardPassword);
		//
		JdbcTemplate lineTemplate = JDBCTemplateCache.getLineJdbcTemplate(line);
		//	没有数据源
		if (lineTemplate == null) {
			return null;
		}
		//	插入sql,
		String insertSql = "INSERT INTO Dosage (Storage,Material,station,fall,RecAmnt,PlanAmnt,FactAmnt,Flag,piece,id) VALUES (?,?,?,?,?,?,?,?,?,?)";
		//	拼接参数
		List<Object[]> params = new ArrayList<>();
		//	返回插入成功的数据id
		List<Long> expendBIds = new ArrayList<>();
		//	待删除的盘表数据
		Set<String> delDosList = new HashSet<>();
		for (int i = 0, s = labExpends.size(); i < s; i++) {
			LabExpendVoB labExpendB = labExpends.get(i);
			//	工控料仓
			String storage = labExpendB.getControlStorage();
			//	工控材料
			String material = labExpendB.getControlMaterial();
			//	工控含税率
			Double watFull = labExpendB.getControlWater();
			// 	配方值
			Double recAmnt = labExpendB.getOptimizeQuantity();
			//	设定值
			Double planAmnt = labExpendB.getControlSetQuantity();
			//	实际用量
			Double factAmnt = labExpendB.getControlRealQuantity();
			//	标识
			String flag = "1";
			//	消耗id,带字幕的32位随机数
			String dosId = RandomUtils.genLetterString(32);
			//	转大写
			dosId = dosId.toUpperCase();
			//	时间戳?
			Double savestamp = null;
			//	工控机的盘id
			String conBatchId = labExpendB.getConBatchId();
			Long lineId1 = labExpendB.getLineId();
			SysLine sysLine = sysLineDao.selectById(lineId1);
			Long controlLineId = 1l;
			if (sysLine != null) {
				controlLineId = sysLine.getControlLineId();
			}
			Object[] param = {storage, material, controlLineId, watFull, recAmnt, planAmnt, factAmnt, flag, conBatchId, dosId};
			params.add(param);
			//	本条记录id
			Long id = labExpendB.getId();
			expendBIds.add(id);
			//	盘数据
			String conExpendId = labExpendB.getConExpendId();
			conExpendId = "'" + conExpendId + "'";
			delDosList.add(conExpendId);
		}
		//	根据盘消耗删除数据
		String join = String.join(",", delDosList);
		String delDosSql = "delete from Dosage where piece in (" + join + ")";
		// lineTemplate.update(delDosSql);
		//	插入消耗数据
		int[] ints = lineTemplate.batchUpdate(insertSql, params);

		return expendBIds;
	}

}
